<template>
  <div class="menu-list">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <div class="search-item">
        <div class="search-label">菜单名称</div>
        <el-input
          v-model="searchForm.name"
          placeholder="请输入菜单名称"
          clearable
          class="search-input"
          @keyup.enter="handleSearch"
        />
      </div>
      <div class="search-item">
        <div class="search-label">是否为菜单</div>
        <el-select
          v-model="searchForm.isMenu"
          placeholder="全部类型"
          clearable
          class="search-select"
        >
          <el-option label="是" :value="true" />
          <el-option label="否" :value="false" />
        </el-select>
      </div>
      <el-button type="primary" @click="handleSearch" class="search-button">搜索</el-button>
      <el-button @click="handleReset" class="search-button">重置</el-button>
    </div>

    <!-- 工具栏 -->
    <div class="button-group">
      <el-button type="primary" class="custom-button" @click="handleCreate">新增菜单</el-button>
      <el-button type="danger" class="custom-button" @click="handleBatchDelete">批量删除</el-button>
    </div>

    <!-- 菜单表格 -->
    <el-table
      :data="filteredData"
      row-key="id"
      border
      style="width: 100%"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column prop="permissionId" label="序号" min-width="60" align="center" />
      <el-table-column prop="code" label="菜单编码" min-width="120" align="center" />
      <el-table-column prop="name" label="菜单名称" min-width="120" align="center" />
      <el-table-column prop="path" label="访问路径" min-width="180" align="center" />
      <el-table-column prop="isMenu" label="菜单类" min-width="80" align="center">
        <template #default="{ row }">
          <el-tag :type="row.isMenu ? 'success' : 'info'">
            {{ row.isMenu ? '是' : '否' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="200" align="center">
        <template #default="{ row }">
          <el-button type="primary" size="small" class="operation-button" @click="handleEdit(row)"
            >编辑</el-button
          >
          <el-button type="danger" size="small" class="operation-button" @click="handleDelete(row)"
            >删除</el-button
          >
          <el-button
            v-if="row.isMenu"
            type="success"
            size="small"
            class="operation-button"
            @click="handleCreateChild(row)"
            >新增子菜单</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="custom-pagination">
      <span>共 {{ total }} 条</span>
      <select v-model="pagination.pageSize" @change="handlePageSizeChange" class="page-size-select">
        <option v-for="size in pagination.pageSizes" :key="size" :value="size">
          {{ size }}条/页
        </option>
      </select>
      <button
        :disabled="pagination.currentPage === 1"
        @click="handlePageChange(pagination.currentPage - 1)"
        class="pagination-button"
      >
        &lt;
      </button>
      <button
        v-for="page in totalPages"
        :key="page"
        :class="['pagination-button', { 'current-page': page === pagination.currentPage }]"
        @click="handlePageChange(page)"
      >
        {{ page }}
      </button>
      <button
        :disabled="pagination.currentPage === totalPages"
        @click="handlePageChange(pagination.currentPage + 1)"
        class="pagination-button"
      >
        &gt;
      </button>
      <span>前往</span>
      <input
        type="number"
        v-model.number="pagination.jumpPage"
        @keyup.enter="handleJumpPage"
        class="pagination-input"
        :max="totalPages"
        :min="1"
      />
      <span>页</span>
    </div>

    <!-- 表单对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
      top="250px"
      @closed="handleDialogClose"
    >
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px">
        <el-form-item label="菜单编码" prop="code">
          <el-input v-model="formData.code" placeholder="请输入唯一编码" />
        </el-form-item>
        <el-form-item label="菜单名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入菜单名称" />
        </el-form-item>
        <el-form-item label="访问路径" prop="path">
          <el-input v-model="formData.path" placeholder="请输入路由路径" />
        </el-form-item>
        <el-form-item label="菜单" prop="isMenu">
          <el-select v-model="formData.isMenu">
            <el-option label="是" :value="true" />
            <el-option label="否" :value="false" />
          </el-select>
        </el-form-item>
        <el-form-item label="父级菜单" prop="parentId" v-if="isChildMenu">
          <el-input v-model="formData.parentName" disabled />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { getMenuList } from '@/api/permission'
import { createMenu } from '@/api/permission'

export default {
  name: 'MenuManagement',
  data() {
    return {
      // 数据存储
      rawData: [],
      filteredData: [],
      selectedRows: [],

      // 搜索表单
      searchForm: {
        isMenu: null,
        name: '',
      },

      // 分页配置
      pagination: {
        pageSizes: [10, 20, 30, 50],
        pageSize: 10,
        currentPage: 1,
        jumpPage: 1, // 这里改为1
      },

      // 对话框相关
      dialogVisible: false,
      dialogType: 'create',
      isChildMenu: false,
      formData: {
        code: '',
        name: '',
        path: '',
        isMenu: true,
        parentId: null,
        parentName: ''
      },

      // 表单验证规则
      formRules: {
        code: [{ required: true, message: '请输入菜单编码', trigger: 'blur' }],
        name: [{ required: true, message: '请输入菜单名称', trigger: 'blur' }],
        path: [{ required: true, message: '请输入访问路径', trigger: 'blur' }],
        isMenu: [{ required: true, message: '请选择菜单类型', trigger: 'change' }],
      },
    }
  },
  computed: {
    // 分页数据
    paginatedData() {
      const start = (this.pagination.currentPage - 1) * this.pagination.pageSize
      return this.filteredData.slice(start, start + this.pagination.pageSize)
    },

    // 分页信息
    total() {
      return this.filteredData.length
    },
    totalPages() {
      return Math.ceil(this.total / this.pagination.pageSize) || 1
    },

    // 对话框标题
    dialogTitle() {
      return {
        create: '新增菜单',
        edit: '编辑菜单',
        child: '添加子菜单',
      }[this.dialogType]
    },

    treeData() {
      return this.filteredData // filteredData 保持树结构
    },
  },
  mounted() {
    this.fetchData()
  },
  methods: {
    // 数据获取
    async fetchData() {
      try {
        const treeData = await getMenuList()
        this.rawData = treeData
        this.filteredData = treeData
        if (!treeData.length) {
          this.$message.warning('暂无菜单数据')
        }
      } catch (error) {
        this.$message.error('数据加载失败')
      }
    },

    // 树形结构过滤
    filterTree(data, filterFn) {
      return data
        .map((item) => {
          const children = item.children ? this.filterTree(item.children, filterFn) : []
          if (filterFn(item) || children.length) {
            return { ...item, children }
          }
          return null
        })
        .filter(Boolean)
    },

    // 搜索处理
    handleSearch() {
      const filterFn = (item) => {
        const typeMatch =
          this.searchForm.isMenu !== null ? item.isMenu === this.searchForm.isMenu : true
        const nameMatch = this.searchForm.name
          ? item.name.includes(this.searchForm.name.trim())
          : true
        return typeMatch && nameMatch
      }
      this.filteredData = this.filterTree(this.rawData, filterFn)
    },

    // 重置搜索
    handleReset() {
      this.searchForm = {
        isMenu: null,
        name: '',
      }
      this.handleSearch()
    },

    // 分页处理
    handlePageChange(page) {
      this.pagination.currentPage = page
    },
    // 页大小变化
    handlePageSizeChange() {
      this.pagination.currentPage = 1
    },
    handleJumpPage() {
      if (this.pagination.jumpPage >= 1 && this.pagination.jumpPage <= this.totalPages) {
        this.pagination.currentPage = this.pagination.jumpPage
      } else {
        this.$message.warning('请输入有效的页码')
      }
    },
    // 其他方法（操作处理、表单提交等）保持原有实现
    handleCreate() {
      this.dialogType = 'create'
      this.isChildMenu = false
      this.formData = {
        code: '',
        name: '',
        path: '',
        isMenu: true,
        parentId: null,
        parentName: ''
      }
      this.dialogVisible = true
    },

    handleCreateChild(row) {
      this.dialogType = 'child'
      this.isChildMenu = true
      this.formData = {
        code: '',
        name: '',
        path: '',
        isMenu: true,
        parentId: row.id,
        parentName: row.name
      }
      this.dialogVisible = true
    },

    handleEdit(row) {
      this.dialogType = 'edit'
      this.isChildMenu = !!row.parentId
      this.formData = {
        ...row,
        parentName: row.parentName || ''
      }
      this.dialogVisible = true
    },

    async handleSubmit() {
      try {
        await this.$refs.formRef.validate()
        if (this.dialogType === 'create' || this.dialogType === 'child') {
          // 新增菜单
          await createMenu({
            permissionCode: this.formData.code,
            permissionName: this.formData.name,
            path: this.formData.path,
            isMenu: this.formData.isMenu ? '1' : '0',
            fatherId: this.formData.parentId || 0
          })
          this.$message.success('新增成功')
        } else {
          // TODO: 编辑菜单（保留原逻辑）
          this.$message.success('保存成功')
        }
        this.dialogVisible = false
        this.fetchData()
      } catch (e) {
        console.error('表单验证失败:', e)
      }
    },

    handleDialogClose() {
      this.$refs.formRef?.resetFields()
      this.formData = {
        code: '',
        name: '',
        path: '',
        isMenu: true,
        parentId: null,
        parentName: ''
      }
    },

    async handleDelete(row) {
      try {
        await this.$confirm('确认删除该菜单吗？', '提示', {
          type: 'warning'
        })
        // TODO: 调用删除API
        // await deleteMenu(row.id)
        this.$message.success('删除成功')
        this.fetchData()
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('删除失败')
        }
      }
    },

    async handleBatchDelete() {
      if (!this.selectedRows.length) {
        this.$message.warning('请选择要删除的菜单')
        return
      }
      try {
        await this.$confirm(`确认删除选中的 ${this.selectedRows.length} 个菜单吗？`, '提示', {
          type: 'warning'
        })
        // TODO: 调用批量删除API
        // const ids = this.selectedRows.map(row => row.id)
        // await batchDeleteMenu(ids)
        this.$message.success('批量删除成功')
        this.fetchData()
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('批量删除失败')
        }
      }
    },

    handleSelectionChange(selection) {
      this.selectedRows = selection
    },
  },
}
</script>

<style scoped>
.menu-list {
  padding: 20px;
  background-color: #f9f9f9;
}

/* 搜索栏样式 */
.search-bar {
  display: flex;
  align-items: center;
  gap: 15px;
  flex-wrap: nowrap;
  margin-bottom: 20px;
}
.search-item {
  display: flex;
  align-items: center;
  gap: 5px;
}
.search-label {
  white-space: nowrap;
  font-size: 14px;
}
.search-input,
.search-select {
  width: 200px;
}
.search-button {
  min-width: 80px;
  padding: 6px 10px;
}

/* 工具栏样式 */
.button-group {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
  flex-wrap: nowrap;
  align-items: center;
}
.custom-button {
  white-space: nowrap;
  padding: 5px 10px;
  min-width: 80px;
  text-align: center;
  border-radius: 4px;
}

/* 表格字体缩小 */
.el-table {
  font-size: 13px !important;
  background: #fff;
  border-radius: 8px;
}
.el-table th,
.el-table td {
  padding: 6px 2px;
  white-space: normal !important;
  word-break: break-all;
}

/* 分页样式 */
.custom-pagination {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-top: 20px;
  font-size: 16px;
}
.page-size-select {
  border: 1px solid #dcdfe6;
  outline: none;
  box-shadow: none;
  background: #fff;
}
.pagination-button {
  padding: 2px 6px;
  border: 1px solid #ccc;
  border-radius: 4px;
  min-width: 30px;
}
.pagination-button.current-page {
  background-color: #409eff;
  color: #fff;
  border-color: #409eff;
}
.pagination-input {
  width: 40px;
  text-align: center;
  padding: 2px;
  outline: none;
  box-shadow: none;
  border: 1px solid #dcdfe6;
  background: #fff;
}

/* 其余样式保持原有即可 */
.operation-button {
  min-width: 60px;
  margin-right: 8px;
  border-radius: 6px;
  padding: 5px 10px;
  font-size: 13px;
}
</style>
